<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1100px">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="调出仓库" prop="outWarehouseId">
            <el-select
              v-model="formData.outWarehouseId"
              placeholder="请输入调出仓库"
              :clearable="true"
              :disabled="isEdit || isShow"
            >
              <el-option
                v-for="dict in materialWarehouse"
                :key="dict.id"
                :label="dict.warehouseName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="调入仓库" prop="inWarehouseId">
            <el-select
              v-model="formData.inWarehouseId"
              placeholder="请输入调入仓库"
              :disabled="isEdit || isShow"
            >
              <el-option
                v-for="dict in materialWarehouse"
                :key="dict.id"
                :label="dict.warehouseName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系人电话" prop="contactMobile">
            <el-input
              v-model="formData.contactMobile"
              placeholder="请输入联系人电话"
              :clearable="true"
              :disabled="isShow"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人姓名" prop="contactName">
            <el-input
              v-model="formData.contactName"
              placeholder="请输入联系人姓名"
              :clearable="true"
              :disabled="isShow"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              placeholder="请输入备注"
              :clearable="true"
              type="textarea"
              :disabled="isShow"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form-item :style="{ display: isShow ? 'none' : 'block' }">
      <el-button @click="clickAddMaterial">添加物资</el-button>
      <el-button @click="clickDeleteMaterial">删除物资</el-button>
    </el-form-item>
    <Table
      :columns="columns"
      :data="formData.details"
      save-key="MaterialTransferEdit"
      :row-style="rowStyle"
      @row-click="handleRowClick"
      height="400"
    >
      <template #number="{ row }">
        <InputNumber v-model="row.number" class="!w-100px" :disabled="isShow" type="decimal" />
      </template>
      <template #batchNo="{ row }">
        <el-input
          v-model="row.batchNo"
          class="!w-100px"
          :disabled="isShow"
          @blur="handleBlurBatchNo(row)"
        />
      </template>
      <template #productionDate="{ row }">
        <el-date-picker
          v-model="row.productionDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 130px !important"
          :disabled="isShow"
          @change="handleChangeProductionDate(row)"
        />
      </template>
      <template #expireDate="{ row }">
        <el-date-picker
          v-model="row.expireDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 130px !important"
          :disabled="isShow"
          @change="handleChangeExpireDate(row)"
        />
      </template>
    </Table>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <MaterialStockSelect ref="materialStockSelectRef" @select-value="handleSelectMaterialStock" />
</template>
<script setup name="MaterialTransferEdit" lang="ts">
import * as MaterialWarehouseApi from '@/api/material/warehouse'
import MaterialStockSelect from '../materialStock/MaterialStockSelect.vue'
import * as MaterialTransferApi from '@/api/material/transfer'
import * as MaterialStockApi from '@/api/material/stock'
import * as MaterialTransferModel from '@/model/material/order/MaterialTransfer'
import * as MaterialTransferDetailModel from '@/model/material/order/MaterialTransferDetail'
import { MaterialTransferStatusEnum } from '@/utils/constants'
interface MaterialTransferDetailEdit extends MaterialTransferDetailModel.MaterialTransferDetail {
  'material.materialName': string
  'material.category.categoryName': string
  'material.price': string
  'material.materialSpecification': string
  stockNumber: string
  operateType: string
}
interface MaterialTransferEdit extends MaterialTransferModel.MaterialTransfer {
  details: MaterialTransferDetailEdit[]
}
const materialStockSelectRef = ref()
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const isEdit = ref(false)
const isShow = ref(false)
const formData = ref<MaterialTransferEdit>({
  id: undefined,
  transferNo: '',
  outWarehouseId: undefined,
  inWarehouseId: undefined,
  status: 1,
  remark: '',
  contactName: '',
  contactMobile: '',
  details: []
})
const materialWarehouse = ref()
const message = useMessage()
let formType = ''
const { t } = useI18n()
const formRules = reactive({
  outWarehouseId: [{ required: true, message: '调出仓库不能为空', trigger: 'blur' }],
  inWarehouseId: [{ required: true, message: '调入仓库不能为空', trigger: 'blur' }]
})
const tableCurrentRow = ref()
const columns = ref([
  {
    label: '物资名称',
    prop: 'material.materialName'
  },
  {
    label: '物资类别名称',
    prop: 'material.category.categoryName'
  },
  {
    label: '销售单价',
    prop: 'material.price'
  },
  {
    label: '物资规格',
    prop: 'material.materialSpecification'
  },
  {
    label: '库存',
    prop: 'stockDetail.stockNumber'
  },
  {
    label: '数量',
    prop: 'number',
    slot: 'number',
    minWidth: '100'
  },
  {
    label: '批次号',
    prop: 'batchNo',
    slot: 'batchNo',
    minWidth: '100'
  },
  {
    label: '生产日期',
    prop: 'productionDate',
    slot: 'productionDate',
    minWidth: '130'
  },
  {
    label: '有效期',
    prop: 'expireDate',
    slot: 'expireDate',
    minWidth: '130'
  }
])
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType = type
  resetForm()
  materialWarehouse.value = await MaterialWarehouseApi.simpleList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    isEdit.value = true
    try {
      formData.value = await MaterialTransferApi.singleGet(id)
      if (formData.value.status != MaterialTransferStatusEnum.PENDING_REVIEW) {
        isShow.value = true
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MaterialTransferEdit
    if (formType === 'create') {
      await MaterialTransferApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await MaterialTransferApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
  emit('success')
}

/** table行的style的回调方法 */
const rowStyle = ({ row }) => {
  if (row?.operateType == 'delete') {
    return { display: 'none' }
  } else return {}
}

/** table行点击事件 */
const handleRowClick = (row: MaterialTransferDetailEdit | undefined) => {
  tableCurrentRow.value = row
}
/** 重置表单 */
const resetForm = () => {
  isShow.value = false
  isEdit.value = false
  formData.value = {
    id: undefined,
    transferNo: '',
    outWarehouseId: undefined,
    inWarehouseId: undefined,
    status: 1,
    remark: '',
    contactName: '',
    contactMobile: '',
    details: []
  }
  formRef.value?.resetFields()
}

const clickAddMaterial = () => {
  if (formData.value.outWarehouseId === undefined) {
    message.alertError('请选择调出仓库')
    return
  }
  materialStockSelectRef.value.open({
    warehouseId: { value: formData.value.outWarehouseId, isDisabled: true }
  })
}

const clickDeleteMaterial = () => {
  if (tableCurrentRow.value === undefined) {
    message.alertError('请选择要删除的物资')
    return
  }
  if (formType === 'create' || tableCurrentRow.value.id == '') {
    const index = formData.value.details.indexOf(tableCurrentRow.value)
    formData.value.details.splice(index, 1)
  } else {
    tableCurrentRow.value.operateType = 'delete'
  }
}

const handleSelectMaterialStock = (selectMaterialInfoList) => {
  selectMaterialInfoList.forEach((element) => {
    const detail = {
      id: undefined,
      transferId: formType === 'create' ? undefined : formData.value.id,
      materialId: element.materialId,
      'material.materialName': element.material.materialName,
      'material.category.categoryName': element.material.category.categoryName,
      'material.price': element.price,
      'material.materialSpecification': element.material.materialSpecification,
      stockNumber: element.stockNumber,
      number: 1,
      outNumber: 0,
      inNumber: 0,
      batchNo: element.batchNo,
      productionDate: element.productionDate,
      expireDate: element.expireDate,
      operateType: 'new'
    }
    formData.value.details.push(detail)
  })
}

const handleBlurBatchNo = (row) => {
  stockChange(row)
}

const handleChangeProductionDate = (row) => {
  stockChange(row)
}

const handleChangeExpireDate = (row) => {
  stockChange(row)
}

const stockChange = async (row) => {
  const materialStockInfo = await MaterialStockApi.singleGetByDetail({
    warehouseId: formData.value.outWarehouseId,
    materialId: row.materialId,
    batchNo: row.batchNo,
    productionDate: row.productionDate,
    expireDate: row.expireDate
  })
  row.currentStockNumber = materialStockInfo != undefined ? materialStockInfo.stockNumber : ''
}
</script>
